<template>
  <el-page-header icon="" title="企业门户网站管理系统">
    <template #content>
      <span class="text-large font-600 mr-3"> 个人中心 </span>
    </template>
  </el-page-header>
  <el-row :gutter="20" class="el-row">
    <el-col :span="8">
      <el-card class="box-card">
        <el-avatar :size="100" :src="avatarUrl" />
        <h3>
          {{ store.state.userInfo.username }}
        </h3>
        <h3>
          {{ store.state.userInfo.role === 1 ? "管理员" : "编辑" }}
        </h3>
      </el-card>
    </el-col>
    <el-col :span="16">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>个人信息</span>
          </div>
        </template>
        <el-form
          ref="userFormRef"
          style="max-width: 600px"
          :model="userForm"
          :rules="userFormRules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select
              v-model="userForm.gender"
              placeholder="Select"
              style="width: 100%"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="个人简介" prop="introduction">
            <el-input type="textarea" v-model="userForm.introduction" />
          </el-form-item>
          <el-form-item label="头像" prop="avatar">
            <el-upload
              class="avatar-uploader"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handlechange"
            >
              <img
                v-if="userForm.avatar"
                :src="userForm.avatar"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()"> 更新 </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { useStore } from "vuex";
import { computed, ref, reactive } from "vue";
//导入ele图标
import { Plus } from "@element-plus/icons-vue";
import axios from "axios";

//获取登陆成功后后端返回的用户信息
const store = useStore();
//获取用户头像-计算属性
const avatarUrl = computed(() => {
  return store.state.userInfo.avatar
    ? store.state.userInfo.avatar
    : `https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png`; //默认是一只猫头像
});
//其他登陆后的用户信息
const { username, gender, introduction, avatar } = store.state.userInfo;
const userFormRef = ref();
const userForm = reactive({
  username,
  gender,
  introduction,
  avatar,
	file:null
});
//element 的表单验证规则
const userFormRules = reactive({
  //失去焦点时验证
  username: [{ required: true, message: "请输入名字", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  introduction: [{ required: true, message: "请输入介绍", trigger: "blur" }],
  avatar: [{ required: true, message: "请上传头像", trigger: "blur" }],
});
//element 性别下拉框的选项
const options = [
  { value: 0, label: "保密" },
  { value: 1, label: "男" },
  { value: 2, label: "女" },
];
//element头像每次选择完图片之后的回调，获取头像地址的回调
const handlechange = (file: any) => {
  //raw是文件原生对象，包含了文件的原始数据和信息
  // console.log("头像上传", file.raw);
  //URL.createObjectURL() 是浏览器提供的 API，用于将一个文件（或 Blob 对象）转换成临时的 URL 地址，y也就是回显。以便在网页上直接引用该文件（例如显示图片、播放音视频、下载文件等）。
  userForm.avatar = URL.createObjectURL(file.raw);
	//提交给后端用的file对象
	userForm.file = file.raw;
};
//提交表单 更新提交
const submitForm = () => {
	//.validate()是Element Plus表单组件的表单验证方法，用于在提交前检查用户输入是否符合预设规则
	userFormRef.value.validate((valid: any) => {
		if (valid) {
			// console.log("submit-输入正确 获取双向绑定登陆账号值", userForm);
			//new FormData() 的作用功能：创建一个空的 FormData 对象，用于封装需要通过 HTTP multipart/form-data 格式发送的数据（尤其是文件上传场景）。
			const params=new FormData();
			for(let i in userForm){
				//.append追加
				params.append(i,userForm[i]);
			}
      //这个打印出来的params是一个异常：TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:3:28； 视频中也没有展开看他的展开是什么！
			console.log("params",params);
			axios.post("/adminapi/user/upload",params,{
				headers: {
          //表示请求体包含文件上传或其他表单数据
					"Content-Type": "multipart/form-data",

          // "Authorization": `Bearer ${localStorage.getItem("token")}`, // 添加 token

				},
			}).then(res => {
				console.log("头像上传成功", res.data);
				
			}).catch(err => {
				console.log("头像上传失败", err);
			})
			
		}
	});
};
</script>

<style scoped lang="scss">
.el-row {
  margin-top: 20px;
  .box-card {
    margin-top: 20px;
  }
}
//element 头像
:deep() {
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
.avatar {
  width: 178px;
  height: 178px;
}
</style>
